package com.xie.o2o.controller.local;

import com.google.common.collect.Maps;
import com.xie.o2o.dto.LocalAuthExecution;
import com.xie.o2o.entity.LocalAuth;
import com.xie.o2o.entity.PersonInfo;
import com.xie.o2o.enums.LocalAuthStateEnum;
import com.xie.o2o.service.LocalAuthService;
import com.xie.o2o.util.HttpServletUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @create: xie
 */
@Controller
@RequestMapping(value = "/local", method = {RequestMethod.GET, RequestMethod.POST})
public class LocalAuthController {
    private final static Logger log = LoggerFactory.getLogger(LocalAuthController.class);
    @Autowired
    private LocalAuthService localAuthService;

    /**
     * 绑定平台账号
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/bindlocalauth", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> bindLocalAuth(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        //获取输入的账号密码
        String username = HttpServletUtil.getString(request, "username");
        String password = HttpServletUtil.getString(request, "password");
        //获取当前用户信息,通过微信登录后，便能获取到用户信息
        PersonInfo user = (PersonInfo) request.getSession().getAttribute("user");
        //非空判断，要求当前用户账号密码和session不为空
        if (username != null && password != null && user != null && user.getUserId() != null) {
            //创建localAuth对象并赋值
            LocalAuth localAuth = new LocalAuth();
            localAuth.setUsername(username);
            localAuth.setPassword(password);
            localAuth.setPersonInfo(user);
            try {
                //绑定账号
                LocalAuthExecution localAuthExecution = localAuthService.bindLocalAuth(localAuth);
                if (localAuthExecution.getState() == LocalAuthStateEnum.SUCCESS.getState()) {
                    map.put("success", true);
                } else {
                    map.put("success", false);
                    map.put("errMsg", localAuthExecution.getStateInfo());
                }
            } catch (Exception e) {
                map.put("success", false);
                map.put("errMsg", e.toString());
                log.error("绑定平台账号错误"+e.toString());
                throw new RuntimeException("绑定平台账号错误");
            }
        } else {
            map.put("success", false);
            map.put("errMsg", "用户名和密码均不能为空");
        }
        return map;
    }

    /**
     * 修改密码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/changelocalpwd", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> changeLocalPwd(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        //获取输入的账号、旧密码和新密码
        String username = HttpServletUtil.getString(request, "username");
        String password = HttpServletUtil.getString(request, "password");
        String newpassword = HttpServletUtil.getString(request, "newpassword");
        //获取当前用户信息,通过微信登录后，便能获取到用户信息
        PersonInfo user = (PersonInfo) request.getSession().getAttribute("user");
        //非空判断，要求当前用户账号密码和session不为空,新旧密码不相同
        if (username != null && password != null && newpassword != null && user != null && user.getUserId() != null && !password.equals(newpassword)) {
            try {
                //查看原先账号，是否和输入的一致，不一致认为是非法操作
                LocalAuth localAuthByUserId = localAuthService.getLocalAuthByUserId(user.getUserId());
                if (localAuthByUserId == null || !localAuthByUserId.getUsername().equals(username)) {
                    //不一致则退出
                    map.put("success", false);
                    map.put("errMsg", "输入账号非该用户账号");
                    return map;
                }
                //修改平台账号密码
                LocalAuthExecution localAuthExecution = localAuthService.modifyLocalAuth(user.getUserId(), username, password, newpassword);
                if (localAuthExecution.getState() == LocalAuthStateEnum.SUCCESS.getState()) {
                    map.put("success", true);
                } else {
                    map.put("success", false);
                    map.put("errMsg", localAuthExecution.getStateInfo());
                }
            } catch (RuntimeException e) {
                log.error("修改密码失败："+e.getMessage());
                throw new RuntimeException("修改密码失败");
            }
        } else {
            map.put("success", false);
            map.put("errMsg", "请输入完整账号信息");
        }
        return map;
    }

    /**
     * 用户登录
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/logincheck", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> loginCheck(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        //获取输入的账号密码
        String username = HttpServletUtil.getString(request, "username");
        String password = HttpServletUtil.getString(request, "password");
        //非空校验
        if (username != null && password != null) {
            //传入账号和密码去获取平台账号信息
            LocalAuth la = localAuthService.getLocalAuthByUsernameAndPwd(username, password);
            if (la != null) {
                //若能获取到信息则登录成功
                map.put("success", true);
                //在session里设置用户信息
                request.getSession().setAttribute("user", la.getPersonInfo());
            } else {
                map.put("success", false);
                map.put("errMsg", "用户名或密码错误");
            }
        } else {
            map.put("success", false);
            map.put("errMsg", "账号和密码不能为空");
        }
        return map;
    }

    /**
     * 退出登录，注销session
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> logout(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        request.getSession().setAttribute("user", null);
        map.put("success", true);
        return map;
    }

}
